package com.tongweb.catalina.startup;

import com.tongweb.catalina.Container;
import com.tongweb.catalina.Engine;
import com.tongweb.catalina.Host;
import com.tongweb.catalina.LifecycleException;
import com.tongweb.catalina.LifecycleListener;
import com.tongweb.catalina.LifecycleState;
import com.tongweb.catalina.Server;
import com.tongweb.catalina.Service;
import com.tongweb.catalina.connector.Connector;
import com.tongweb.catalina.connector.ThanosConnector;
import com.tongweb.catalina.core.AprLifecycleListener;
import com.tongweb.catalina.core.JMXServer;
import com.tongweb.catalina.core.StandardHost;
import com.tongweb.catalina.core.StandardServer;
import com.tongweb.catalina.core.ThanosStandardEngine;
import com.tongweb.catalina.core.ThanosStandardHost;
import com.tongweb.catalina.core.ThanosStandardService;
import com.tongweb.catalina.deploy.NamingResourcesImpl;
import com.tongweb.catalina.snmp.SnmpService;
import com.tongweb.config.ConfigTool;
import com.tongweb.config.bean.AccessLog;
import com.tongweb.config.bean.AjpListener;
import com.tongweb.config.bean.AsyncLoggerConfig;
import com.tongweb.config.bean.AuthRealm;
import com.tongweb.config.bean.HttpListener;
import com.tongweb.config.bean.JmxService;
import com.tongweb.config.bean.LogService;
import com.tongweb.config.bean.ModuleLogLevels;
import com.tongweb.config.bean.SecurityService;
import com.tongweb.config.bean.VirtualHost;
import com.tongweb.config.bean.WebContainer;
import com.tongweb.config.event.ConfigEventManager;
import com.tongweb.config.event.ConfigListener;
import com.tongweb.juli.logging.Log;
import com.tongweb.juli.logging.LogFactory;
import com.tongweb.log.LogConfigListener;
import com.tongweb.log.TongwebLogManager;
import com.tongweb.server.TongWebListener;
import com.tongweb.tongejb.commonj.WMManager;
import com.tongweb.util.Utils;
import com.tongweb.web.configlistener.SecurityConfigListener;
import com.tongweb.web.configlistener.a;
import com.tongweb.web.thanos.startup.Configuration;
import com.tongweb.web.thanos.startup.LastStepListener;
import com.tongweb.web.util.descriptor.web.ContextResource;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

public class ThanosCatalina extends Catalina {
    public static final String DEFAULT_REALM_NAME = "defaultRealm";

    private static final Log a = LogFactory.getLog(ThanosCatalina.class);

    private static String b = "server";

    private volatile long c = 0L;

    private Server dserver;

    public static Server staticDserver;

    private Service e;

    private Engine fgne = getEngine();

    private SnmpService g;

    private SecurityConfigListener h = null;

    private static Set isht = new HashSet();

    private static ThanosCatalina j;

    private LastStepListener k;

    private Map l = new ConcurrentHashMap();

    private Map m = new ConcurrentHashMap();

    private static int n = 6;

    private Map p = new HashMap();

    private Map q = new HashMap();

    private String r = "server";

    private NamingResourcesImpl nresourceimpl;

    private a t = null;

    private ConfigEventManager u = null;

    private Server v = null;

    private static boolean w = Boolean.valueOf(System.getProperty("service.start", "false")).booleanValue();

    private static final String x = System.getProperty("tongweb.home");

    private ThanosConnector y;

    private static Map z = new HashMap();

    private static String[] A = new String[]{"com.tongweb.server.ThanosServerListener", "com.tongweb.catalina.core.AprLifecycleListener", "com.tongweb.catalina.core.JreMemoryLeakPreventionListener", "com.tongweb.catalina.mbeans.GlobalResourcesLifecycleListener", "com.tongweb.catalina.core.ThreadLocalLeakPreventionListener", "com.tongweb.server.MonitorLifecycleListener"};

    public static ThanosCatalina getInstance() {
        return j;
    }

    public LastStepListener getLsl() {
        return this.k;
    }

    public void setLsl(LastStepListener paramLastStepListener) {
        this.k = paramLastStepListener;
    }

    public Map getDeployers() {
        return this.l;
    }

    public void setDeployers(Map paramMap) {
        this.l = paramMap;
    }

    public Map getHosts() {
        return this.m;
    }

    public void setHosts(Map paramMap) {
        this.m = paramMap;
    }

    public SnmpService getSnmpService() {
        return this.g;
    }

    public void setSnmpService(SnmpService paramSnmpService) {
        this.g = paramSnmpService;
    }

    public synchronized void refreshHostCache() {
        Container[] arrayOfContainer;
        int i = (arrayOfContainer = this.fgne.findChildren()).length;
        for (byte b = 0; b < i; b++) {
            if (arrayOfContainer[b] instanceof StandardHost) {
                StandardHost standardHost = (StandardHost) arrayOfContainer[b];
                this.m.put(standardHost.getName(), standardHost);
                LifecycleListener[] arrayOfLifecycleListener;
                int j = (arrayOfLifecycleListener = standardHost.findLifecycleListeners()).length;
                for (byte b1 = 0; b1 < j; b1++) {
                    LifecycleListener lifecycleListener;
                    if (arrayOfLifecycleListener[b1] instanceof HostConfig) {
                        lifecycleListener = (HostConfig) arrayOfLifecycleListener[b1];
                        this.l.put(standardHost.getName(), lifecycleListener);
                    }
                }
            }
        }
    }

    public Map getConnectorMap() {
        return this.p;
    }

    public Map getMapperedHost() {
        return this.q;
    }

    public ThanosCatalina() {
        j = this;
    }

    public void init() {
        ConfigTool.getRoot();
        initDirs();
        initNaming();
        initStreams();
        LogManager.getLogManager();
        LogConfigListener logConfigListener = new LogConfigListener();
        ConfigEventManager configEventManager;
        (configEventManager = ConfigEventManager.getInstance()).addListeners((ConfigListener) logConfigListener, LogService.class);
        configEventManager.addListeners((ConfigListener) logConfigListener, ModuleLogLevels.class);
        configEventManager.addListeners((ConfigListener) logConfigListener, AsyncLoggerConfig.class);
    }

    public static boolean isTemporaryLicense() {
        boolean bool = true;
        String str = com.tongweb.catalina.startup.f.g();
        if (str != null && !str.equals(""))
            try {
                int i;
                if ((i = Integer.parseInt(str)) == -1)
                    bool = false;
            } catch (Exception exception) {
            }
        return bool;
    }

    public static c getEdition() {
        c c = com.tongweb.catalina.startup.c.e;
        String str = com.tongweb.catalina.startup.f.b();
        if (str == null)
            return c;
        if (c.a.a(str)) {
            c = c.a;
        } else if (c.b.a(str)) {
            c = c.b;
        } else if (c.c.a(str)) {
            c = c.c;
        } else if (c.d.a(str)) {
            c = c.d;
        }
        return c;
    }

    private static void e() {
        StringBuffer stringBuffer;
        (stringBuffer = new StringBuffer()).append("License信息: ");
        stringBuffer.append("客户信息: 东方通国产容器");
        stringBuffer.append("; 项目名称: IT基础组件监控平台");
        stringBuffer.append("; 到期时间: 永久无限期");
        a.warn(stringBuffer.toString());
    }

    private static int f() {
        com.tongweb.catalina.startup.f.f();
        String str = com.tongweb.catalina.startup.f.g();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        int i = 0;
        boolean bool = false;
        try {
            if (str != null && !str.equals("")) {
                try {
                    int j;
                    if ((j = Integer.parseInt(str)) == -1)
                        bool = true;
                } catch (Exception exception) {
                }
                if (!bool) {
                    Date date;
                    long l1 = (date = simpleDateFormat.parse(str)).getTime();
                    long l2 = System.currentTimeMillis();
                    i = (int) ((l1 - l2) / 86400000L);
                }
            }
        } catch (ParseException parseException) {
            System.out.println(parseException.getMessage());
        }
        if (bool)
            i = Integer.MAX_VALUE;
        return i;
    }

    private static void g() {
        com.tongweb.config.bean.Server server = ConfigTool.getRoot().getServer();
        ArrayList<Integer> arrayList2;
        (arrayList2 = new ArrayList<Integer>()).add(Integer.valueOf(server.getShutdownPort()));
        WebContainer webContainer;
        for (HttpListener httpListener : (webContainer = server.getWebContainer()).getHttpListener())
            arrayList2.add(httpListener.getPort());
        for (AjpListener ajpListener : webContainer.getAjpListener())
            arrayList2.add(ajpListener.getPort());
        JmxService jmxService;
        if ((jmxService = server.getJmxService()) != null)
            arrayList2.add(jmxService.getPort());
        com.tongweb.config.bean.SnmpService snmpService;
        if ((snmpService = server.getSnmpService()) != null && snmpService.isEnable() != null && snmpService.isEnable().booleanValue())
            arrayList2.add(Integer.valueOf(snmpService.getPort()));
        ArrayList<Integer> arrayList1 = new ArrayList(arrayList2.size());
        Iterator<Integer> iterator = arrayList2.iterator();
        while (iterator.hasNext()) {
            int i;
            if (!Utils.isPortAvailable(i = ((Integer) iterator.next()).intValue()))
                arrayList1.add(Integer.valueOf(i));
        }
        if (!arrayList1.isEmpty()) {
            iterator = arrayList1.iterator();
            while (iterator.hasNext()) {
                int i = ((Integer) iterator.next()).intValue();
                a.fatal("address already in use: " + i);
            }
            System.exit(1);
        }
    }

    public void load() {
        LogManager logManager = LogManager.getLogManager();
        TongwebLogManager tongwebLogManager = (TongwebLogManager) logManager;
        boolean bool0 = tongwebLogManager.isVerbose();
        if (logManager != null && logManager instanceof TongwebLogManager && !bool0) {
            tongwebLogManager.updateVerbose(true);
        }
        System.out.println("License will never expire.");
        //e();
        (new b()).start();
        if (this.c == 0L)
            this.c = System.currentTimeMillis();
        g();
        init();
        getServer();
        ThanosCatalina thanosCatalina;
        (thanosCatalina = this).nresourceimpl = new NamingResourcesImpl();
        thanosCatalina.dserver.setGlobalNamingResources(thanosCatalina.nresourceimpl);
        loadApmJar();
        thanosCatalina = this;

        int i = ConfigTool.getRoot().getServer().getJmxService().getPort().intValue();
        String str2 = ConfigTool.getRoot().getServer().getJmxService().getAddress();
        try {
            ServerSocket serverSocket = new ServerSocket(i, 100, InetAddress.getByName(str2));
            serverSocket.close();
            if (!str2.equals("0.0.0.0")) {
                ServerSocket serverSocket1 = new ServerSocket(i, 100, InetAddress.getByName("0.0.0.0"));
                serverSocket1.close();
            }
        } catch (IOException iOException) {
            Logger logger = Logger.getLogger("admin");
            String str3 = h();
            String str4;
            if ((str4 = System.getProperty("tongweb.home")) != null) {
                try {
                    str4 = (new File(str4)).getCanonicalPath();
                } catch (IOException iOException1) {
                    logger.log(Level.SEVERE, "Can not get tongweb location.");
                }
                if (str3 != null)
                    try {
                        str3 = (new File(str3)).getCanonicalPath();
                    } catch (IOException iOException1) {
                        logger.log(Level.SEVERE, "openRemote JMX Port error. ", iOException);
                        thanosCatalina.stop();
                    }
                if (str4.equals(str3)) {
                    logger.log(Level.SEVERE, "Instance already running.");
                } else {
                    logger.log(Level.SEVERE, "openRemote JMX Port error. ", iOException);
                    thanosCatalina.stop();
                }
            } else {
                logger.log(Level.SEVERE, "Can not get tongweb location.");
            }
            if (w)
                i();
            System.exit(1);
        }
        l();
        this.t = new a();
        this.t.a(this);
        this.u = ConfigEventManager.getInstance();
        this.u.addListeners((ConfigListener) this.t, WebContainer.class);
        this.u.addListeners((ConfigListener) this.t, AccessLog.class);
        initSecurityService();
        this.fgne = getEngine();
        this.fgne.setParentClassLoader(this.parentClassLoader);
        this.fgne.setDefaultHost(this.r);
        this.fgne.addLifecycleListener(new EngineConfig());
        ((ThanosStandardEngine) this.fgne).configureEngine();
        try {
            j();
        } catch (Exception et) {
            et.printStackTrace();
        }
        k();
        refreshHostCache();
        getServer().setCatalina(this);
        getServer().setCatalinaHome(Bootstrap.getCatalinaHomeFile());
        getServer().setCatalinaBase(Bootstrap.getCatalinaBaseFile());
        try {
            getServer().init();
        } catch (Exception et) {
            et.printStackTrace();
        }
        initRemoteEJBServer();
        initSnmpService();
    }

    public void initDirs() {
        super.initDirs();
    }

    public void start() {
        Iterator<TongWebListener> iterator2 = isht.iterator();
        while (iterator2.hasNext()) {
            iterator2.next().beforeStart();
        }
        Logger logger = Logger.getLogger(getClass().getName());
        int ii = ConfigTool.getRoot().getServer().getJmxService().getPort().intValue();
        LinkedList<Integer> linkedList = new LinkedList();
        LinkedList<String> linkedList1 = new LinkedList();
        linkedList.add(Integer.valueOf(ii));
        ii = Configuration.getServerBean().getShutdownPort();
        linkedList.add(Integer.valueOf(ii));
        for (HttpListener httpListener : ConfigTool.getRoot().getServer().getWebContainer().getHttpListener()) {
            linkedList.add(httpListener.getPort());
            linkedList1.add(httpListener.getName());
        }
        for (AjpListener ajpListener : ConfigTool.getRoot().getServer().getWebContainer().getAjpListener()) {
            linkedList.add(ajpListener.getPort());
            linkedList1.add(ajpListener.getName());
        }

        for (VirtualHost virtualHost : ConfigTool.getRoot().getServer().getWebContainer().getVirtualHost())
            linkedList1.add(virtualHost.getName());
        for (String str : linkedList1) {
            byte b = 0;
            Iterator<String> iterator = linkedList1.iterator();
            while (iterator.hasNext()) {
                String str1;
                if ((str1 = iterator.next()).equals(str) && ++b >= 2) {
                    Logger logger1;
                    (logger1 = Logger.getLogger("admin")).log(Level.SEVERE, "listener or Host name " + str + " is duplicate.");
                    if (w)
                        i();
                    System.exit(1);
                }
            }
        }
        logger.log(Level.INFO, "Starting TongWeb Server...");
        try {
            String str;
            if ((str = ConfigTool.getRoot().getServer().getJmxService().getProtocol()).equals("mp")) {
                JMXServer.openRemotePortMP();
            } else if (str.equals("rmi")) {
                JMXServer.openRemotePort();
            } else {
                System.out.println("wrong protocol tw7 support the rmi or mp");
            }
        } catch (Exception exception2) {
            exception2.printStackTrace();
            stop();
            if (w)
                i();
            System.exit(1);
        }
        if (getServer() == null)
            load();
        if (getServer() == null) {
            a.fatal("Cannot start server. Server instance is not configured.");
            return;
        }
        System.nanoTime();
        try {
            Class.forName("com.oneapm.si.nodeservice.MaskFactory");
            getServer().start();
        } catch (LifecycleException lifecycleException) {
            a.error("Catalina.start: ", (Throwable) lifecycleException);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //loadRemoteEjbServerApp();
        List<HttpListener> list1 = Configuration.getHttpListenerBeans();
        for (com.tongweb.config.bean.HttpListener httpListener : list1) {
            Connector connector;
            if ((connector = (Connector) this.p.get(httpListener.getName())) != null) {
                if ("FAILED".equals(connector.getState().name()))
                    httpListener.setStatus("failed");
                if (httpListener.getStatus().equals("stopped"))
                    try {
                        connector.stop();
                    } catch (LifecycleException lifecycleException) {
                        a.error("httplistener is fail to stop: ", (Throwable) lifecycleException);
                    }
            }
        }
        List<AjpListener> list2 = Configuration.getAjpListenerBeans();
        for (AjpListener ajpListener : list2) {
            Connector connector;
            if ((connector = (Connector) this.p.get(ajpListener.getName())) != null) {
                if ("FAILED".equals(connector.getState().name()))
                    ajpListener.setStatus("failed");
                if (ajpListener.getStatus().equals("stopped"))
                    try {
                        connector.stop();
                    } catch (LifecycleException lifecycleException) {
                        a.error("ajplistener is fail to stop: ", (Throwable) lifecycleException);
                    }
            }
        }
        List<VirtualHost> list3 = Configuration.getHosts();
        for (VirtualHost virtualHost : list3) {
            ThanosStandardHost thanosStandardHost;
            if (!(thanosStandardHost = (ThanosStandardHost) this.fgne.findChild(virtualHost.getName())).isStatus())
                try {
                    thanosStandardHost.stop();
                } catch (LifecycleException lifecycleException) {
                    a.error("host is fail to stop: ", (Throwable) lifecycleException);
                }
        }
        if ((System.getProperty("isZeroValidPrimaryKey") == null)) {
            ii = 0;
        } else {
            ii = (Boolean.valueOf(System.getProperty("isZeroValidPrimaryKey")).booleanValue()) ? 1 : 0;
        }
        if (ii != 0)
            //Helper.isZeroValidPrimaryKey = true;
            try {
                WMManager.getInstance().load();
            } catch (Exception exception) {
                System.out.println("load workmanagers failed ! cause : " + exception.getCause());
            }
        ThanosCatalina thanosCatalina = this;
        try {
            Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass("com.tongweb.tw.thanos.TongwebLoader");
            Method method = clazz.getMethod("getInstance", null);
            thanosCatalina.k = (LastStepListener) method.invoke(null, null);
            thanosCatalina.k.event();
        } catch (Exception exception2) {
            exception2.printStackTrace();
        } finally {
            System.gc();
        }
        if (this.useShutdownHook) {
            if (this.shutdownHook == null)
                this.shutdownHook = new d(this);
            Runtime.getRuntime().addShutdownHook(this.shutdownHook);
            LogManager.getLogManager();
        }
        if (w) {
            File file = new File(x + "/conf/state-success");
            try {
                file.createNewFile();
            } catch (IOException iOException) {
                a.info("create Flag File Failed!");
                iOException.printStackTrace();
            }
        }
        long l = System.currentTimeMillis() - this.c;
        logger.log(Level.INFO, "TongWeb server startup complete in " + l + " ms.");
        if ((thanosCatalina = this).g != null)
            try {
                long l1 = System.currentTimeMillis();
                thanosCatalina.g.start();
                long l2 = System.currentTimeMillis() - l1;
                (logger = Logger.getLogger(thanosCatalina.getClass().getName())).log(Level.INFO, "Snmp server startup complete in " + l2 + " ms.");
            } catch (LifecycleException lifecycleException) {
                a.warn("start snmp Service failed.", (Throwable) lifecycleException);
            }
        Iterator<TongWebListener> iterator1 = isht.iterator();
        while (iterator1.hasNext()) {
            TongWebListener tongWebListener = iterator1.next();
            tongWebListener.afterStart();
        }
        if (this.await) {
            await();
            iterator1 = isht.iterator();
            while (iterator1.hasNext()) {
                TongWebListener tongWebListener = iterator1.next();
                tongWebListener.beforeStop();
            }
            try {
                WMManager.getInstance().shutdown();
            } catch (Exception exception) {
                System.out.println("shutdown workmanagers failed ! cause : " + exception.getCause());
            }
            stop();
            JMXServer.closeRemote();
            iterator1 = isht.iterator();
            while (iterator1.hasNext()) {
                TongWebListener tongWebListener = iterator1.next();
                tongWebListener.afterStop();
            }
            System.exit(0);
        }
    }

    public void initRemoteEJBServer() {
        try {
            Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass("com.tongweb.tongejb.config.EELoader");
            Method method = clazz.getMethod("load", null);
            method.invoke(null, null);
            return;
        } catch (Exception exception2) {
            exception2.printStackTrace();
            return;
        }
    }

    public void initSnmpService() {
        com.tongweb.config.bean.SnmpService snmpService;
        if ((snmpService = ConfigTool.getRoot().getServer().getSnmpService()) == null || snmpService.isEnable() == null || !snmpService.isEnable().booleanValue())
            return;
        this.g = new SnmpService();
        this.g.setAuthKey(snmpService.getAuthKey());
        this.g.setEngineID(snmpService.getEngineID());
        this.g.setPort(snmpService.getPort());
        this.g.setPrivKey(snmpService.getPrivKey());
        this.g.setTransportType(snmpService.getTransportType());
        this.g.setSecurityName(snmpService.getSecurityName());
        this.g.setVersion(snmpService.getVersion().intValue());
        this.g.setAddress(snmpService.getAddress());
    }


    public void initSecurityService() {
        this.h = new SecurityConfigListener();
        Configuration.getSecurityService();
        this.u.addListeners((ConfigListener) this.h, SecurityService.class);
        this.u.addListeners((ConfigListener) this.h, AuthRealm.class);
    }

    private static String h() {
        try {
            Integer integer = Integer.valueOf(9060);
            for (HttpListener httpListener : ConfigTool.getRoot().getServer().getWebContainer().getHttpListener()) {
                if ("system-http-listener".equals(httpListener.getName())) {
                    integer = httpListener.getPort();
                    break;
                }
            }
            URL uRL;
            HttpURLConnection httpURLConnection;
            (httpURLConnection = (HttpURLConnection) (uRL = new URL("http://127.0.0.1:" + integer + "/console/notinrealm/rest/commons/location")).openConnection()).setConnectTimeout(2000);
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader;
            String str;
            return str = (bufferedReader = new BufferedReader(new InputStreamReader(inputStream))).readLine();
        } catch (Exception exception) {
            return null;
        }
    }

    private static void i() {
        File file = new File(x + "/conf/state-fail");
        try {
            file.createNewFile();
            return;
        } catch (IOException iOException) {
            a.info("create Fail Flag File Failed!");
            iOException.printStackTrace();
            return;
        }
    }

    public Server getServer() {
        if (this.dserver != null)
            return this.dserver;
        this.dserver = (Server) new StandardServer();
        int i = Configuration.getServerBean().getShutdownPort();
        this.dserver.setPort(i);
        this.dserver.setShutdown("TW7-SHUTDOWN");
        this.e = (Service) new ThanosStandardService();
        this.e.setName("TONGWEB");
        this.dserver.addService(this.e);
        staticDserver = this.dserver;
        return this.dserver;
    }

    public Service getService() {
        getServer();
        return this.e;
    }

    public Engine getEngine() {
        if (this.fgne == null) {
            getServer();
            this.fgne = (Engine) new ThanosStandardEngine();
            this.fgne.setName("TONGWEB");
            this.fgne.setDefaultHost(this.r);
            this.e.setContainer(this.fgne);
        }
        return this.fgne;
    }

    private void j() {
        List<?> list2;
        Iterator<?> iterator1 = (list2 = Configuration.getHttpListenerBeans()).iterator();
        while (iterator1.hasNext()) {
            HttpListener httpListener;
            if ((httpListener = (HttpListener) iterator1.next()).getCreateTime() == null) {
                SimpleDateFormat simpleDateFormat;
                String str = (simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
                httpListener.setCreateTime(str);
            }
            a(httpListener);
        }
        List<?> list1;
        Iterator<?> iterator2 = (list1 = Configuration.getAjpListenerBeans()).iterator();
        while (iterator2.hasNext()) {
            AjpListener ajpListener;
            if ((ajpListener = (AjpListener) iterator2.next()).getCreateTime() == null) {
                SimpleDateFormat simpleDateFormat;
                String str = (simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
                ajpListener.setCreateTime(str);
            }
            a(ajpListener);
        }
    }

    private Connector a(AjpListener paramAjpListener) {
        String str3 = paramAjpListener.getStatus();
        if (str3.equalsIgnoreCase("stopped")) {
            this.u.addListeners((ConfigListener) this.t, paramAjpListener, Boolean.TRUE);
            return null;
        }
        int i = paramAjpListener.getPort().intValue();
        ThanosCatalina thanosCatalina = this;
        ThanosStandardHost thanosStandardHost = (ThanosStandardHost) thanosCatalina.fgne.findChild("server");
        if (thanosStandardHost != null) {
            int[] arrayOfInt1;
            int[] arrayOfInt2;
            int j = (arrayOfInt2 = arrayOfInt1 = thanosStandardHost.getPorts()).length;
            byte b = 0;
            while (true) {
                if (b < j) {
                    int k;
                    if ((k = arrayOfInt2[b]) != i) {
                        b++;
                        continue;
                    }
                    break;
                }
                arrayOfInt2 = new int[arrayOfInt1.length + 1];
                System.arraycopy(arrayOfInt1, 0, arrayOfInt2, 0, arrayOfInt1.length);
                arrayOfInt2[arrayOfInt1.length] = i;
                thanosStandardHost.setPorts(arrayOfInt2);
                break;
            }
        }
        String str2 = paramAjpListener.getName();
        if ("failed".equals(paramAjpListener.getStatus()))
            paramAjpListener.setStatus("started");
        String str4 = ThanosConnector.getProtocolHandlerClass(false, paramAjpListener.getIoMode());
        ThanosConnector thanosConnector;
        (thanosConnector = new ThanosConnector(str4)).setName(str2);
        thanosConnector.configureAjpListener(paramAjpListener);
        str2 = paramAjpListener.getDefaultVirtualHost();
        thanosConnector.setDefaultHost(str2);
        this.e.addConnector((Connector) thanosConnector);
        this.u.addListeners((ConfigListener) this.t, paramAjpListener, Boolean.TRUE);
        this.p.put(paramAjpListener.getName(), thanosConnector);
        LifecycleState lifecycleState2 = thanosConnector.getState();
        if (lifecycleState2.equals(LifecycleState.FAILED)) {
            paramAjpListener.setStatus("failed");
            //throw new LifecycleException("fail to create a new connector!");
        }
        String str1;
        LifecycleState lifecycleState1;
        if ((str1 = paramAjpListener.getStatus()).equalsIgnoreCase("stopped") && (lifecycleState1 = thanosConnector.getState()).equals(LifecycleState.STARTED))
            try {
                thanosConnector.stop();
            } catch (LifecycleException lifecycleException) {
                a.error("fail to stop http listener!");
            }
        return (Connector) thanosConnector;
    }

    public ThanosConnector getHttpConnector() {
        return this.y;
    }

    public void setHttpConnector(ThanosConnector paramThanosConnector) {
        this.y = paramThanosConnector;
    }

    private Connector a(HttpListener paramHttpListener) {
        String str2;
        if ((str2 = paramHttpListener.getStatus()).equalsIgnoreCase("stopped")) {
            this.u.addListeners((ConfigListener) this.t, paramHttpListener, Boolean.TRUE);
            return null;
        }
        str2 = paramHttpListener.getName();
        if ("failed".equals(paramHttpListener.getStatus()))
            paramHttpListener.setStatus("started");
        String str3 = ThanosConnector.getProtocolHandlerClass(true, paramHttpListener.getIoMode());
        this.y = new ThanosConnector(str3);
        this.y.setName(str2);
        this.y.ConfigureHttpListener(paramHttpListener);
        str2 = paramHttpListener.getDefaultVirtualHost();
        this.y.setDefaultHost(str2);
        this.e.addConnector((Connector) this.y);
        this.u.addListeners((ConfigListener) this.t, paramHttpListener, Boolean.TRUE);
        this.p.put(paramHttpListener.getName(), this.y);
        String str1;
        LifecycleState lifecycleState;
        if ((str1 = paramHttpListener.getStatus()).equalsIgnoreCase("stopped") && (lifecycleState = this.y.getState()).equals(LifecycleState.STARTED))
            try {
                this.y.stop();
            } catch (LifecycleException lifecycleException) {
                a.error("fail to stop http listener!");
            }
        return (Connector) this.y;
    }

    private void k() {
        List<VirtualHost> list = Configuration.getHosts();
        for (VirtualHost virtualHost : list)
            a(virtualHost);
    }

    private Host a(VirtualHost paramVirtualHost) {
        ThanosStandardHost thanosStandardHost;
        ThanosStandardHost.createHost(thanosStandardHost = new ThanosStandardHost(), paramVirtualHost, this.p, z, this.q);
        this.u.addListeners((ConfigListener) this.t, paramVirtualHost, Boolean.TRUE);
        this.fgne.addChild((Container) thanosStandardHost);
        boolean bool = paramVirtualHost.isStatus();
        thanosStandardHost.setStatus(bool);
        return (Host) thanosStandardHost;
    }

    private void l() {
        try {
            String[] arrayOfString = A;
            for (byte b = 0; b < 6; b++) {
                String str;
                Class<?> clazz;
                LifecycleListener lifecycleListener = (LifecycleListener) (clazz = Class.forName(str = arrayOfString[b])).newInstance();
                this.dserver.addLifecycleListener(lifecycleListener);
            }
        } catch (ClassNotFoundException classNotFoundException) {
            a.error("class not found!", classNotFoundException);
        } catch (InstantiationException instantiationException) {
            a.error("InstantiationException", instantiationException);
        } catch (IllegalAccessException illegalAccessException) {
            a.error("IllegalAccessException", illegalAccessException);
        }
        AprLifecycleListener.useAprConnector = true;
    }

    public void updateHttpConnector(HttpListener paramHttpListener) {
        Connector connector = (Connector) this.p.get(paramHttpListener.getName());
        if (paramHttpListener.getName().equalsIgnoreCase("system-http-listener")) {
            a.info("Admin listener has changed, please restart server!");
            return;
        }
        if (connector != null) {
            HttpListener httpListener = paramHttpListener;
            Connector connector1;
            Container[] arrayOfContainer;
            Engine engine;
            int i = (arrayOfContainer = arrayOfContainer = (engine = (connector1 = connector).getService().getContainer()).findChildren()).length;
            for (byte b = 0; b < i; b++) {
                ThanosStandardHost thanosStandardHost;
                Container container;
                int[] arrayOfInt = new int[((thanosStandardHost = (ThanosStandardHost) (container = arrayOfContainer[b])).getPorts()).length];
                for (byte b1 = 0; b1 < (thanosStandardHost.getPorts()).length; b1++) {
                    if (thanosStandardHost.getPorts()[b1] == connector1.getPort()) {
                        arrayOfInt[b1] = httpListener.getPort().intValue();
                    } else {
                        arrayOfInt[b1] = thanosStandardHost.getPorts()[b1];
                    }
                }
                thanosStandardHost.setPorts(arrayOfInt);
            }
            deleteConnector(connector);
            this.u.removedListeners((ConfigListener) this.t, paramHttpListener, Boolean.TRUE);
            this.p.remove(paramHttpListener.getName());
        }
        addHttpConnector(paramHttpListener);
    }

    public void updateHttpConnectorStatus(HttpListener paramHttpListener, String paramString) {
        Connector connector;
        if ((connector = (Connector) this.p.get(paramHttpListener.getName())) != null) {
            if (paramString.equals("stopped")) {
                deleteConnector(connector);
                return;
            }
            if (paramString.equals("started")) {
                this.u.removedListeners((ConfigListener) this.t, paramHttpListener, Boolean.TRUE);
                deleteConnector(connector);
                addHttpConnector(paramHttpListener);
                return;
            }
        } else if (paramString.equals("started")) {
            this.u.removedListeners((ConfigListener) this.t, paramHttpListener, Boolean.TRUE);
            addHttpConnector(paramHttpListener);
        }
    }

    public void updateAjpConnectorStatus(AjpListener paramAjpListener, String paramString) {
        Connector connector;
        if ((connector = (Connector) this.p.get(paramAjpListener.getName())) != null) {
            if (paramString.equals("stopped")) {
                deleteConnector(connector);
                return;
            }
            if (paramString.equals("started")) {
                this.u.removedListeners((ConfigListener) this.t, paramAjpListener, Boolean.TRUE);
                deleteConnector(connector);
                addAjpConnector(paramAjpListener);
                return;
            }
        } else if (paramString.equals("started")) {
            this.u.removedListeners((ConfigListener) this.t, paramAjpListener, Boolean.TRUE);
            addAjpConnector(paramAjpListener);
        }
    }

    public void deleteHttpConnector(HttpListener paramHttpListener) {
        Connector[] arrayOfConnector = this.e.findConnectors();
        String str = String.valueOf(paramHttpListener.getPort());
        int i = (arrayOfConnector = arrayOfConnector).length;
        for (byte b = 0; b < i; b++) {
            Connector connector;
            String str1 = String.valueOf((connector = arrayOfConnector[b]).getPort());
            if (str.equals(str1)) {
                this.p.remove(paramHttpListener.getName());
                this.q.remove(paramHttpListener.getName());
                deleteConnector(connector);
                this.u.removedListeners((ConfigListener) this.t, paramHttpListener, Boolean.TRUE);
            }
        }
    }

    public void deleteConnector(Connector paramConnector) {
        Connector[] arrayOfConnector = this.e.findConnectors();
        int i;
        String str = String.valueOf(i = paramConnector.getPort());
        int j = (arrayOfConnector = arrayOfConnector).length;
        for (byte b = 0; b < j; b++) {
            Connector connector;
            String str1 = String.valueOf((connector = arrayOfConnector[b]).getPort());
            if (str.equals(str1)) {
                this.e.removeConnector(connector);
                try {
                    connector.destroy();
                } catch (LifecycleException lifecycleException) {
                    lifecycleException.printStackTrace();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        }
    }

    public Connector addHttpConnector(HttpListener paramHttpListener) {
        Connector connector;
        ((ThanosConnector) (connector = a(paramHttpListener))).setMapperedHost((Set) this.q.get(paramHttpListener.getName()));
        return connector;
    }

    public void updateAjpConnector(AjpListener paramAjpListener) {
        Connector connector;
        if ((connector = (Connector) this.p.get(paramAjpListener.getName())) != null) {
            AjpListener ajpListener = paramAjpListener;
            Connector connector1;
            Engine engine;
            Container[] arrayOfContainer;
            int i = (arrayOfContainer = arrayOfContainer = (engine = (connector1 = connector).getService().getContainer()).findChildren()).length;
            for (byte b = 0; b < i; b++) {
                ThanosStandardHost thanosStandardHost;
                Container container;
                int[] arrayOfInt = new int[((thanosStandardHost = (ThanosStandardHost) (container = arrayOfContainer[b])).getPorts()).length];
                for (byte b1 = 0; b1 < (thanosStandardHost.getPorts()).length; b1++) {
                    if (thanosStandardHost.getPorts()[b1] == connector1.getPort()) {
                        arrayOfInt[b1] = ajpListener.getPort().intValue();
                    } else {
                        arrayOfInt[b1] = thanosStandardHost.getPorts()[b1];
                    }
                }
                thanosStandardHost.setPorts(arrayOfInt);
            }
            deleteConnector(connector);
            this.u.removedListeners((ConfigListener) this.t, paramAjpListener, Boolean.TRUE);
            this.p.remove(paramAjpListener.getName());
        }
        addAjpConnector(paramAjpListener);
    }

    public Connector addAjpConnector(AjpListener paramAjpListener) {
        Connector connector;
        ((ThanosConnector) (connector = a(paramAjpListener))).setMapperedHost((Set) this.q.get(paramAjpListener.getName()));
        return connector;
    }

    public void deleteAjpConnector(AjpListener paramAjpListener) {
        Connector[] arrayOfConnector = this.e.findConnectors();
        String str = String.valueOf(paramAjpListener.getPort());
        int j = (arrayOfConnector = arrayOfConnector).length;
        byte b;
        for (b = 0; b < j; b++) {
            Connector connector;
            String str1 = String.valueOf((connector = arrayOfConnector[b]).getPort());
            if (str.equals(str1)) {
                deleteConnector(connector);
                this.q.remove(paramAjpListener.getName());
                this.u.removedListeners((ConfigListener) this.t, paramAjpListener, Boolean.TRUE);
            }
        }
        int i = paramAjpListener.getPort().intValue();
        ThanosStandardHost thanosStandardHost;
        ThanosCatalina thanosCatalina;
        if ((thanosStandardHost = (ThanosStandardHost) (thanosCatalina = this).fgne.findChild("server")) != null) {
            int[] arrayOfInt = thanosStandardHost.getPorts();
            j = -1;
            for (b = 0; b < arrayOfInt.length; b++) {
                if (arrayOfInt[b] == i) {
                    j = b;
                    break;
                }
            }
            if (j >= 0) {
                int[] arrayOfInt1 = new int[arrayOfInt.length - 1];
                i = 0;
                for (byte b1 = 0; b1 < arrayOfInt.length; b1++) {
                    if (b1 != j)
                        arrayOfInt1[i++] = arrayOfInt[b1];
                }
                thanosStandardHost.setPorts(arrayOfInt1);
            }
        }
    }

    public void updateHost(VirtualHost paramVirtualHost) {
        ThanosStandardHost thanosStandardHost;
        ThanosStandardHost.updateHost(thanosStandardHost = (ThanosStandardHost) this.fgne.findChild(paramVirtualHost.getName()), paramVirtualHost, this.p, z, this.q);
    }

    public void addHost(VirtualHost paramVirtualHost) {
        a(paramVirtualHost);
    }

    public void deleteHost(VirtualHost paramVirtualHost) {
        if (paramVirtualHost == null) {
            a.error("no virtual server is delete!!");
            return;
        }
        String str = paramVirtualHost.getName();
        Container[] arrayOfContainer1 = this.fgne.findChildren();
        for (byte b1 = 0; b1 < arrayOfContainer1.length; b1++) {
            if (arrayOfContainer1[b1].getName().equals(this.fgne.getDefaultHost())) {
                arrayOfContainer1[b1] = null;
                break;
            }
        }
        Container[] arrayOfContainer2;
        int i = (arrayOfContainer2 = arrayOfContainer1).length;
        for (byte b2 = 0; b2 < i; b2++) {
            Container container;
            if ((container = arrayOfContainer2[b2]) != null) {
  /*              if (str.equals(this.f.getDefaultHost()))
                    throw new LifecycleException("Cannot delete admin virtual-host.");*/
                if (str.equals(container.getName())) {
                    Iterator<Map.Entry> iterator = this.q.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<?, Set> entry;
                        ((Set) (entry = iterator.next()).getValue()).remove(container);
                    }
                    Container[] arrayOfContainer3;
                    Container[] arrayOfContainer4;
                    int j = (arrayOfContainer4 = arrayOfContainer3 = container.findChildren()).length;

                    try {
                        for (byte b = 0; b < j; b++) {
                            Container container1 = arrayOfContainer4[b];
                            container.removeChild(container1);
                            container1.destroy();
                        }
                        container.stop();
                        container.destroy();
                    } catch (Exception exception) {
                        a.warn("the virtual host destroy fail!");
                    }
                }
            }
        }
    }

    public void updateAccessLog(WebContainer paramWebContainer) {
        Container[] arrayOfContainer;
        int i = (arrayOfContainer = arrayOfContainer = this.fgne.findChildren()).length;
        for (byte b = 0; b < i; b++) {
            Container container = arrayOfContainer[b];
            String str = null;
            if (((ThanosStandardHost) container).getAccesslog() != null)
                str = ((ThanosStandardHost) container).getAccesslog().getDirectory();
            ((ThanosStandardHost) container).reconfigureAccessLog(paramWebContainer.getAccessLog(), str);
        }
    }


    private static boolean m() {
        try {
            Iterator<HttpListener> iterator = Configuration.getServerBean().getWebContainer().getHttpListener().iterator();
            while (iterator.hasNext()) {
                HttpListener httpListener;
                if (!Utils.isPortAvailable((httpListener = iterator.next()).getPort().intValue()))
                    return true;
            }
        } catch (Exception exception) {
        }
        try {
            Iterator<AjpListener> iterator = Configuration.getServerBean().getWebContainer().getAjpListener().iterator();
            while (iterator.hasNext()) {
                AjpListener ajpListener;
                if (!Utils.isPortAvailable((ajpListener = iterator.next()).getPort().intValue()))
                    return true;
            }
        } catch (Exception exception) {
        }
        try {
            Integer integer;
            if (!Utils.isPortAvailable((integer = Configuration.getServerBean().getJmxService().getPort()).intValue()))
                return true;
        } catch (Exception exception) {
        }
        try {
            int i;
            if (!Utils.isPortAvailable(i = Configuration.getServerBean().getShutdownPort()))
                return true;
        } catch (Exception exception) {
        }
        return false;
    }


    public static boolean IPMatch(String paramString1, String paramString2) {
        return true;
    }

    private static List o() {
        ArrayList<String> arrayList = new ArrayList();
        try {
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                NetworkInterface networkInterface;
                Enumeration<InetAddress> enumeration1 = (networkInterface = enumeration.nextElement()).getInetAddresses();
                while (enumeration1.hasMoreElements()) {
                    InetAddress inetAddress = null;
                    if (enumeration1.nextElement() instanceof java.net.Inet4Address) {
                        inetAddress = (java.net.Inet4Address) enumeration1.nextElement();
                        arrayList.add(inetAddress.getHostAddress().split("%")[0]);
                    }
                    if (inetAddress instanceof java.net.Inet6Address)
                        arrayList.add(inetAddress.getHostAddress().split("%")[0]);
                }
            }
        } catch (Exception exception) {
            System.out.println(exception.getCause().getMessage());
            return arrayList;
        }
        return arrayList;
    }


    static {
        ServiceLoader<TongWebListener> serviceLoader = ServiceLoader.load(TongWebListener.class);
        for (TongWebListener tongWebListener : serviceLoader)
            isht.add(tongWebListener);
    }


    /**
     * 加载资源
     *
     * @author wei.hu
     * @date 2021-11-26
     */
    private void loadApmJar() {
        addConfigureResources();
        addConfigureMaskFactory();
        System.out.println("========== loadApmJar method execute successfully");
    }

    /**
     * 添加资源获取的工厂方法
     *
     * @author wei.hu
     * @date 2021-11-26
     */
    private void addConfigureMaskFactory() {
        ContextResource contextResource = new ContextResource();
        contextResource.setAuth("Container");
        contextResource.setName("global/ServiceProxy");
        contextResource.setDescription("User database that can be updated and saved");
        contextResource.setProperty("pathname", "conf/webtier-users.xml");
        contextResource.setProperty("readonly", "false");
        contextResource.setType("com.tongweb.catalina.UserDatabase");
        contextResource.setProperty("factory", "com.tongweb.catalina.startup.MaskFactoryChild");
        this.dserver.getGlobalNamingResources().resourceRequireExplicitRegistration = true;
        this.dserver.getGlobalNamingResources().addResource(contextResource);
    }

    /**
     * 添加资源
     *
     * @author wei.hu
     * @date 2021-11-26
     */
    private void addConfigureResources() {
        ContextResource contextResource = new ContextResource();
        contextResource.setAuth("Container");
        contextResource.setName("UserDatabase");
        contextResource.setDescription("User database that can be updated and saved");
        contextResource.setType("com.tongweb.catalina.UserDatabase");
        contextResource.setProperty("pathname", "conf/webtier-users.xml");
        contextResource.setProperty("factory", "com.tongweb.catalina.users.MemoryUserDatabaseFactory");
        this.dserver.getGlobalNamingResources().resourceRequireExplicitRegistration = true;
        this.dserver.getGlobalNamingResources().addResource(contextResource);
    }


}
